# -*- coding = utf-8 -*-
# @Time：2022/3/14 13:05
# @Author：3ic
# @File：timeline_selector.py
# @Software：PyCharm

import openpyxl
import xlrd
from PyQt5.QtWidgets import QPushButton, QLineEdit, QComboBox, QFileDialog, QMessageBox


class TimelineSelector:
    def __init__(self, parent_window=None):
        (self.file_choose_btn, self.file_text, self.sheet_chooser_combo) = self._generateComponents()

        self.parent_window = parent_window
        self.setComponentsParent(parent_window)

        self._timeline_path = ''

    def _generateComponents(self):
        file_choose_btn = QPushButton("选择轴表")
        file_choose_btn.resize(70, 25)
        file_choose_btn.clicked.connect(self._selectTimelineFile)
        file_choose_btn.setStyleSheet('font-size:14px;')

        file_text = QLineEdit("")
        file_text.resize(100, 25)
        file_text.setReadOnly(True)
        file_text.setStyleSheet('border:0;background-color:#DCDCDC;')

        sheet_chooser_combo = QComboBox()
        sheet_chooser_combo.resize(110, 25)

        return file_choose_btn, file_text, sheet_chooser_combo

    def _selectTimelineFile(self):
        timeline_path, _ = QFileDialog.getOpenFileName(self.parent_window, "选取单个文件", "", "XLSX Files (*.xlsx)")
        if timeline_path == '':
            return None

        sheet_names = openpyxl.load_workbook(timeline_path).sheetnames
        self.sheet_chooser_combo.clear()
        self.sheet_chooser_combo.addItems(sheet_names)
        self.file_text.setText(timeline_path.split("/")[-1][:-5])
        self._timeline_path = timeline_path

    def setComponentsParent(self, parent_window):
        if self.file_choose_btn.parent() == parent_window:
            return
        self.file_choose_btn.setParent(parent_window)
        self.file_text.setParent(parent_window)
        self.sheet_chooser_combo.setParent(parent_window)
        self.moveComponents((0, 0), (0, 0), (0, 0))

    def moveComponents(self, file_choose_btn_pos: tuple = None, file_textbox_pos: tuple = None,
                       sheet_chooser_combo_pos: tuple = None):
        if file_choose_btn_pos is not None:
            self.file_choose_btn.move(file_choose_btn_pos[0], file_choose_btn_pos[1])
        if file_textbox_pos is not None:
            self.file_text.move(file_textbox_pos[0], file_textbox_pos[1])
        if sheet_chooser_combo_pos is not None:
            self.sheet_chooser_combo.move(sheet_chooser_combo_pos[0], sheet_chooser_combo_pos[1])

    def checkTimeline(self):
        if self._timeline_path == '':
            QMessageBox.critical(self.parent_window, '错误！', '尚未选择轴表文件！', QMessageBox.Ok, QMessageBox.Ok)
            return False
        if self.sheet_chooser_combo.count() < 1:
            QMessageBox.critical(self.parent_window, '错误！', '轴表内无表！', QMessageBox.Ok, QMessageBox.Ok)
            return False
        return True

    def loadTimeLine(self):
        wb = xlrd.open_workbook(self._timeline_path)
        sheet = wb.sheet_by_name(self.sheet_chooser_combo.currentText())
        timeline = []
        sec_delay = 0
        ubtimes = [0, 0, 0, 0, 0, 0, 0]
        rows = []
        for row in range(sheet.nrows):
            cells = sheet.row_values(row)
            if cells[0] == '':
                continue
            elif cells[0] == '*':
                for i in range(5):
                    ubtimes[i + 1] = cells[i + 1]
                continue
            elif cells[0] == '>>':
                sec_delay = 90 - int(cells[1])
                continue

            timeline_row = []
            role_cell_idx = 0
            for idx in range(len(cells)):
                cell = cells[idx]
                if cell == '#':
                    break
                if idx == 0:
                    timeline_row.append(int(cell))
                elif idx == 1:
                    timeline_row.append(int(cell))
                elif cell != '':
                    if role_cell_idx == 0:
                        timeline_row.append(int(cell))
                    elif role_cell_idx == 1:
                        if cell < 0:
                            cell = 9999
                        elif cell < 40:
                            cell = 40
                        timeline_row.append(int(cell))
                    else:
                        cell += ubtimes[timeline_row[-2]]
                        timeline_row.append(cell if cell > 0 else 0)
                    role_cell_idx = (role_cell_idx + 1) % 3

            if len(timeline_row) > 2:
                timeline_row.append('#')
                rows.append(timeline_row)

        for timeline_row in rows:
            timeline_row[0] -= sec_delay
            if 0 < timeline_row[0] < 90:
                timeline.append(tuple(timeline_row))
        timeline.append((-1, -1))
        return tuple(timeline)
